package com.david.http;

import java.io.IOException;

import org.apache.commons.lang3.ArrayUtils;
import org.apache.commons.lang3.StringUtils;
import org.apache.http.Header;
import org.apache.http.HeaderElement;
import org.apache.http.HttpEntity;
import org.apache.http.HttpException;
import org.apache.http.HttpResponse;
import org.apache.http.HttpResponseInterceptor;
import org.apache.http.client.entity.GzipDecompressingEntity;
import org.apache.http.protocol.HttpContext;

public class ResponseInterceptor implements HttpResponseInterceptor {

	public void process(HttpResponse response, HttpContext context)
			throws HttpException, IOException {
		HttpEntity entity = response.getEntity();
		if (entity == null) {
			return;
		}
		Header header = entity.getContentEncoding();
		if (header == null) {
			return;
		}
		HeaderElement[] elements = header.getElements();
		if (ArrayUtils.isEmpty(elements)) {
			return;
		}
		for (HeaderElement element : elements) {
			if (StringUtils.equalsIgnoreCase("gzip", element.getName())) {
				response.setEntity(new GzipDecompressingEntity(response
						.getEntity()));
				return;
			}
		}
	}

}
